<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品管理系统 - 操作日志</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        /* 样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
            color: #606266;
        }
        .app-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .logo-area {
            display: flex;
            align-items: center;
        }
        .logo {
            width: 50px;
            height: 50px;
            margin-right: 15px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
        }
        .system-name {
            font-size: 22px;
            font-weight: bold;
        }
        .nav-menu {
            display: flex;
            background-color: #304156;
            padding: 0 20px;
        }
        .nav-item {
            padding: 15px 20px;
            color: #bfcbd9;
            cursor: pointer;
            transition: all 0.3s;
        }
        .nav-item:hover, .nav-item.active {
            color: #409EFF;
            background-color: #263445;
            border-bottom: 2px solid #409EFF;
        }
        .main-content {
            flex: 1;
            padding: 20px;
        }
        .card-container {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .search-bar {
            margin-bottom: 20px;
            padding: 20px;
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .footer {
            text-align: center;
            padding: 15px 0;
            color: #909399;
            font-size: 14px;
            background-color: #f5f7fa;
            border-top: 1px solid #e6e6e6;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .operation-type-tag {
            margin-right: 5px;
        }
        .time-range-picker {
            width: 350px;
        }
        .no-data {
            text-align: center;
            padding: 40px 0;
            color: #909399;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <header class="header">
        <div class="logo-area">
            <div class="logo">药</div>
            <div class="system-name">药品管理系统</div>
        </div>
        <div>
            <el-dropdown @command="handleUserCommand">
                <span class="el-dropdown-link" style="color: white; cursor: pointer;">
                    {{ currentUser.username }} ({{ formatRole(currentUser.role) }})<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </header>

    <nav class="nav-menu">
        <div class="nav-item" @click="navigateTo('index.html')">首页</div>
        <div class="nav-item" @click="navigateTo('medicine.html')">药品管理</div>
        <div class="nav-item" @click="navigateTo('inventory.html')">库存管理</div>
        <div class="nav-item" @click="navigateTo('sale.html')">销售管理</div>
        <div class="nav-item" @click="navigateTo('user.html')" v-if="currentUser.role === 'admin'">用户管理</div>
        <div class="nav-item active">操作日志</div>
    </nav>

    <main class="main-content">
        <h2 style="margin-bottom: 20px;">操作日志</h2>

        <div class="search-bar">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="操作类型">
                    <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable>
                        <el-option label="添加" value="ADD"></el-option>
                        <el-option label="修改" value="UPDATE"></el-option>
                        <el-option label="删除" value="DELETE"></el-option>
                        <el-option label="销售" value="SALE"></el-option>
                        <el-option label="登录" value="LOGIN"></el-option>
                        <el-option label="登出" value="LOGOUT"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="操作对象">
                    <el-select v-model="searchForm.targetType" placeholder="请选择操作对象" clearable>
                        <el-option label="药品" value="MEDICINE"></el-option>
                        <el-option label="库存" value="INVENTORY"></el-option>
                        <el-option label="用户" value="USER"></el-option>
                        <el-option label="销售" value="SALE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="操作人">
                    <el-input v-model="searchForm.operatorName" placeholder="请输入操作人姓名" clearable></el-input>
                </el-form-item>
                <el-form-item label="操作时间">
                    <el-date-picker
                            v-model="searchForm.timeRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd"
                            class="time-range-picker">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadOperationLogs">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="danger" @click="clearLogs" v-if="currentUser.role === 'admin'">清空日志</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card-container">
            <el-table
                    :data="paginatedLogs"
                    border
                    stripe
                    v-loading="loading">
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="user.username" label="操作人" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.user ? scope.row.user.username : '未知用户' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作类型" width="100">
                    <template slot-scope="scope">
                        <el-tag
                                size="small"
                                :type="getOperationTypeTagType(scope.row.operationType)"
                                class="operation-type-tag">
                            {{ formatOperationType(scope.row.operationType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作对象" width="100">
                    <template slot-scope="scope">
                        <el-tag
                                size="small"
                                type="info">
                            {{ formatTargetType(scope.row.targetType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="targetId" label="对象ID" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.targetId || '无' }}
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="操作描述" min-width="200"></el-table-column>
                <el-table-column prop="operationTime" label="操作时间" width="160">
                    <template slot-scope="scope">
                        {{ formatDateTime(scope.row.operationTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right" v-if="currentUser.role === 'admin'">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger" @click="handleDeleteLog(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div v-if="filteredLogs.length === 0 && !loading" class="no-data">
                <i class="el-icon-document" style="font-size: 48px; margin-bottom: 16px;"></i>
                <p>暂无操作日志数据</p>
            </div>

            <div class="pagination-container" v-if="filteredLogs.length > 0">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="pagination.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="filteredLogs.length">
                </el-pagination>
            </div>
        </div>
    </main>

    <footer class="footer">© 2023 药品管理系统 - 版权所有</footer>

    <!-- 全局加载层 -->
    <div class="loading-overlay" v-if="globalLoading">
        <el-button type="primary" :loading="true">加载中</el-button>
    </div>
</div>

<script>
    // 配置axios默认设置
    axios.defaults.baseURL = 'http://localhost:8080';
    axios.defaults.withCredentials = true; // 确保发送cookie

    // 添加请求拦截器，在请求头中添加会话标识
    axios.interceptors.request.use(
        config => {
            // 从localStorage获取用户信息
            const userStr = localStorage.getItem('currentUser');
            if (userStr) {
                try {
                    const user = JSON.parse(userStr);
                    // 添加用户标识到请求头（如果需要）
                    config.headers['X-User-Id'] = user.id;
                } catch (e) {
                    console.error('解析用户信息失败', e);
                }
            }
            return config;
        },
        error => {
            return Promise.reject(error);
        }
    );

    // 添加响应拦截器，处理未授权情况
    axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if (error.response && error.response.status === 401) {
                // 未授权，跳转到登录页
                window.location.href = 'login.html';
            } else if (error.response && error.response.status === 403) {
                // 权限不足
                Vue.prototype.$message.error('权限不足，无法执行此操作');
            }
            return Promise.reject(error);
        }
    );

    new Vue({
        el: '#app',
        data() {
            return {
                activeNav: 'log',
                currentUser: { id: null, username: '', role: '' },
                searchForm: {
                    operationType: '',
                    targetType: '',
                    operatorName: '',
                    timeRange: []
                },
                allLogs: [], // 存储所有日志数据
                filteredLogs: [], // 存储筛选后的日志数据
                loading: false,
                globalLoading: false,
                pagination: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 0
                }
            };
        },
        computed: {
            // 计算分页后的数据
            paginatedLogs() {
                const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
                const end = start + this.pagination.pageSize;
                return this.filteredLogs.slice(start, end);
            }
        },
        mounted() {
            // 先从本地存储获取用户信息
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                try {
                    this.currentUser = JSON.parse(savedUser);
                } catch (e) {
                    console.error('解析用户信息失败', e);
                }
            }

            this.loadCurrentUser();
            this.loadOperationLogs();
        },
        methods: {
            loadCurrentUser() {
                this.globalLoading = true;
                axios.get('/pms/user/current').then(response => {
                    if (response.data.success) {
                        this.currentUser = response.data.data;
                        localStorage.setItem('currentUser', JSON.stringify(response.data.data));
                    } else {
                        this.$message.error(response.data.message);
                        window.location.href = 'login.html';
                    }
                    this.globalLoading = false;
                }).catch(error => {
                    console.error('获取用户信息失败:', error);
                    this.$message.error('获取用户信息失败');
                    this.globalLoading = false;
                    // 不直接跳转，可能只是会话过期
                });
            },

            loadOperationLogs() {
                this.loading = true;

                // 根据用户角色选择不同的API端点
                const apiUrl = this.currentUser.role === 'admin' ? '/pms/logs/all' : '/pms/logs/my';

                axios.get(apiUrl).then(response => {
                    if (response.data.success) {
                        this.allLogs = response.data.data;
                        this.applyFilters(); // 应用筛选条件
                    } else {
                        this.$message.error(response.data.message);
                        if (response.data.message.includes("未登录") || response.data.message.includes("权限不足")) {
                            window.location.href = 'login.html';
                        }
                    }
                    this.loading = false;
                }).catch(error => {
                    console.error('获取操作日志失败:', error);
                    this.$message.error('获取操作日志失败: ' + (error.response?.data?.message || error.message));
                    this.loading = false;
                });
            },

            // 应用筛选条件
            applyFilters() {
                this.filteredLogs = this.allLogs.filter(log => {
                    // 操作类型筛选
                    if (this.searchForm.operationType && log.operationType !== this.searchForm.operationType) {
                        return false;
                    }

                    // 操作对象筛选
                    if (this.searchForm.targetType && log.targetType !== this.searchForm.targetType) {
                        return false;
                    }

                    // 操作人筛选
                    if (this.searchForm.operatorName) {
                        const username = log.user ? log.user.username : '';
                        if (!username.toLowerCase().includes(this.searchForm.operatorName.toLowerCase())) {
                            return false;
                        }
                    }

                    // 时间范围筛选
                    if (this.searchForm.timeRange && this.searchForm.timeRange.length === 2) {
                        const logDate = new Date(log.operationTime);
                        const startDate = new Date(this.searchForm.timeRange[0]);
                        const endDate = new Date(this.searchForm.timeRange[1]);
                        endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间

                        if (logDate < startDate || logDate > endDate) {
                            return false;
                        }
                    }

                    return true;
                });

                // 重置分页到第一页
                this.pagination.currentPage = 1;
                this.pagination.total = this.filteredLogs.length;
            },

            resetSearch() {
                this.searchForm = {
                    operationType: '',
                    targetType: '',
                    operatorName: '',
                    timeRange: []
                };
                this.applyFilters();
            },

            handleSizeChange(size) {
                this.pagination.pageSize = size;
                this.pagination.currentPage = 1;
            },

            handleCurrentChange(page) {
                this.pagination.currentPage = page;
            },

            handleDeleteLog(log) {
                this.$confirm(`确定要删除这条操作日志吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 注意：后端没有提供删除单条日志的API，这里需要根据实际情况调整
                    this.$message.warning('删除单条日志功能暂未实现');
                    // 实际实现可能需要调用后端API
                    // axios.delete(`/pms/logs/${log.id}`).then(response => {
                    //     if (response.data.success) {
                    //         this.$message.success('删除成功');
                    //         this.loadOperationLogs(); // 重新加载日志
                    //     } else {
                    //         this.$message.error(response.data.message);
                    //     }
                    // }).catch(error => {
                    //     console.error('删除日志失败:', error);
                    //     this.$message.error('删除日志失败');
                    // });
                }).catch(() => {});
            },

            clearLogs() {
                this.$confirm('确定要清空所有操作日志吗？此操作不可恢复！', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 注意：后端没有提供清空日志的API，这里需要根据实际情况调整
                    this.$message.warning('清空日志功能暂未实现');
                    // 实际实现可能需要调用后端API
                    // axios.delete('/pms/logs/clear').then(response => {
                    //     if (response.data.success) {
                    //         this.$message.success('清空日志成功');
                    //         this.loadOperationLogs();
                    //     } else {
                    //         this.$message.error(response.data.message);
                    //     }
                    // }).catch(error => {
                    //     console.error('清空日志失败:', error);
                    //     this.$message.error('清空日志失败');
                    // });
                }).catch(() => {});
            },

            formatDateTime(dateTime) {
                if (!dateTime) return '';
                const date = new Date(dateTime);
                return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
            },

            formatOperationType(type) {
                const typeMap = {
                    'ADD': '添加',
                    'UPDATE': '修改',
                    'DELETE': '删除',
                    'SALE': '销售',
                    'LOGIN': '登录',
                    'LOGOUT': '登出'
                };
                return typeMap[type] || type;
            },

            formatTargetType(type) {
                const typeMap = {
                    'MEDICINE': '药品',
                    'INVENTORY': '库存',
                    'USER': '用户',
                    'SALE': '销售'
                };
                return typeMap[type] || type;
            },

            getOperationTypeTagType(type) {
                const typeMap = {
                    'ADD': 'success',
                    'UPDATE': 'primary',
                    'DELETE': 'danger',
                    'SALE': 'warning',
                    'LOGIN': 'info',
                    'LOGOUT': 'info'
                };
                return typeMap[type] || 'info';
            },

            navigateTo(url) {
                window.location.href = url;
            },

            handleUserCommand(command) {
                if (command === 'profile') {
                    window.location.href = 'profile.html';
                } else if (command === 'logout') {
                    this.handleLogout();
                }
            },

            handleLogout() {
                axios.post('/pms/user/logout').then(response => {
                    if (response.data.success) {
                        this.$message.success(response.data.message);
                        localStorage.removeItem('currentUser');
                        window.location.href = 'login.html';
                    }
                }).catch(error => {
                    console.error('退出登录失败:', error);
                    // 即使API调用失败，也清除本地存储并跳转
                    localStorage.removeItem('currentUser');
                    window.location.href = 'login.html';
                });
            },

            formatRole(role) {
                const roleMap = { 'admin': '管理员', 'sales': '销售员', 'inventory': '库存管理员' };
                return roleMap[role] || role;
            }
        }
    });
</script>
</body>
</html>